package com.facesteel.speech_play.utils;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioDeviceCallback;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.os.Build;
import android.util.Log;

public class BluetoothAudioRouter {
    private static final String TAG = "BluetoothAudioRouter";

    private final Context context;
    private final AudioManager audioManager;
    private final BluetoothAudioListener listener;

    private BroadcastReceiver bluetoothReceiver;
    private AudioDeviceCallback audioDeviceCallback;
    private boolean isBluetoothConnected = false;

    public interface BluetoothAudioListener {
        void onBluetoothConnected();
        void onBluetoothDisconnected();
    }

    public BluetoothAudioRouter(Context context, BluetoothAudioListener listener) {
        this.context = context.getApplicationContext();
        this.listener = listener;
        this.audioManager = (AudioManager) this.context.getSystemService(Context.AUDIO_SERVICE);
    }

    /**
     * 注册蓝牙状态监听器
     */
    public void registerBluetoothListener() {
        // 注册传统广播接收器（兼容所有Android版本）
        registerLegacyBluetoothReceiver();

        // 注册现代设备回调（Android 8.0+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            registerAudioDeviceCallback();
        }

        // 初始化当前蓝牙状态
        updateBluetoothStatus();
    }

    /**
     * 注销蓝牙状态监听器
     */
    public void unregisterBluetoothListener() {
        unregisterLegacyBluetoothReceiver();
        unregisterAudioDeviceCallback();
    }

    /**
     * 强制切换到蓝牙音频路由（如果可用）
     */
    public void switchToBluetooth() {
        if (!isBluetoothAudioAvailable()) {
            Log.w(TAG, "无法切换到蓝牙：无可用设备");
            return;
        }

        try {
            // 停止可能存在的旧SCO连接
            audioManager.stopBluetoothSco();

            // 设置通信模式
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);

            // 启动蓝牙SCO连接
            audioManager.startBluetoothSco();

            // 启用蓝牙SCO音频路由
            audioManager.setBluetoothScoOn(true);

            // 设置扬声器关闭（强制使用蓝牙）
            audioManager.setSpeakerphoneOn(false);

            Log.i(TAG, "已切换到蓝牙音频路由");
        } catch (SecurityException e) {
            Log.e(TAG, "缺少蓝牙权限: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "切换到蓝牙失败: " + e.getMessage());
        }
    }

    /**
     * 切换到正常音频模式
     */
    public void switchToNormalMode(boolean useSpeaker) {
        try {
            // 关闭蓝牙SCO
            audioManager.setBluetoothScoOn(false);
            audioManager.stopBluetoothSco();

            // 恢复正常音频模式
            audioManager.setMode(AudioManager.MODE_NORMAL);

            // 设置扬声器状态
            audioManager.setSpeakerphoneOn(useSpeaker);

            Log.i(TAG, "已切换到正常音频模式，扬声器: " + useSpeaker);
        } catch (Exception e) {
            Log.e(TAG, "切换正常模式失败: " + e.getMessage());
        }
    }

    /**
     * 检查蓝牙音频设备是否可用
     */
    public boolean isBluetoothAudioAvailable() {
        if (audioManager == null) return false;

        // Android 6.0+ 的检查方式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            AudioDeviceInfo[] devices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
            for (AudioDeviceInfo device : devices) {
                if (isBluetoothDeviceType(device.getType())) {
                    return true;
                }
            }
            return false;
        }

        // 旧版Android的检查方式
        return audioManager.isBluetoothScoAvailableOffCall() &&
                (audioManager.isBluetoothScoOn() || audioManager.isBluetoothA2dpOn());
    }

    /**
     * 获取当前蓝牙连接状态
     */
    public boolean isBluetoothConnected() {
        return isBluetoothConnected;
    }

    private void registerLegacyBluetoothReceiver() {
        if (bluetoothReceiver != null) return;

        bluetoothReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                // 蓝牙耳机连接状态变化
                if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                    Log.d(TAG, "蓝牙设备已连接");
                    isBluetoothConnected = true;
                    if (listener != null) listener.onBluetoothConnected();
                }
                // 蓝牙耳机断开连接
                else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                    Log.d(TAG, "蓝牙设备已断开");
                    isBluetoothConnected = false;
                    if (listener != null) listener.onBluetoothDisconnected();
                }
            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);

        context.registerReceiver(bluetoothReceiver, filter);
        Log.d(TAG, "传统蓝牙监听器已注册");
    }

    private void unregisterLegacyBluetoothReceiver() {
        if (bluetoothReceiver != null) {
            try {
                context.unregisterReceiver(bluetoothReceiver);
                bluetoothReceiver = null;
                Log.d(TAG, "传统蓝牙监听器已注销");
            } catch (Exception e) {
                Log.e(TAG, "注销传统蓝牙监听器失败: " + e.getMessage());
            }
        }
    }

    @androidx.annotation.RequiresApi(api = Build.VERSION_CODES.O)
    private void registerAudioDeviceCallback() {
        if (audioDeviceCallback != null) return;

        audioDeviceCallback = new AudioDeviceCallback() {
            @Override
            public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) {
                for (AudioDeviceInfo device : addedDevices) {
                    if (isBluetoothDeviceType(device.getType())) {
                        Log.d(TAG, "蓝牙音频设备已添加: " + device.getProductName());
                        isBluetoothConnected = true;
                        if (listener != null) listener.onBluetoothConnected();
                        return;
                    }
                }
            }

            @Override
            public void onAudioDevicesRemoved(AudioDeviceInfo[] removedDevices) {
                for (AudioDeviceInfo device : removedDevices) {
                    if (isBluetoothDeviceType(device.getType())) {
                        Log.d(TAG, "蓝牙音频设备已移除: " + device.getProductName());
                        isBluetoothConnected = false;
                        if (listener != null) listener.onBluetoothDisconnected();
                        return;
                    }
                }
            }
        };

        audioManager.registerAudioDeviceCallback(audioDeviceCallback, null);
        Log.d(TAG, "现代音频设备回调已注册");
    }

    private void unregisterAudioDeviceCallback() {
        if (audioDeviceCallback != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                audioManager.unregisterAudioDeviceCallback(audioDeviceCallback);
            }
            audioDeviceCallback = null;
            Log.d(TAG, "现代音频设备回调已注销");
        }
    }

    private void updateBluetoothStatus() {
        boolean wasConnected = isBluetoothConnected;
        isBluetoothConnected = isBluetoothAudioAvailable();

        if (wasConnected != isBluetoothConnected) {
            if (isBluetoothConnected) {
                Log.d(TAG, "初始化检测到蓝牙已连接");
                if (listener != null) listener.onBluetoothConnected();
            } else {
                Log.d(TAG, "初始化检测到蓝牙未连接");
                if (listener != null) listener.onBluetoothDisconnected();
            }
        }
    }

    private boolean isBluetoothDeviceType(int deviceType) {
        return deviceType == AudioDeviceInfo.TYPE_BLUETOOTH_SCO ||
                deviceType == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP ||
                deviceType == AudioDeviceInfo.TYPE_BLE_HEADSET ||
                deviceType == AudioDeviceInfo.TYPE_BLE_SPEAKER;
    }
}